import { login, logout, getInfo } from '@/api/login'
import { flowAlert } from '@/api/business'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getAllShop } from '@/api/shop'
import {
  getFeatureList,
  getAllDeviceList,
  getAllDeviceListByShopId
} from '@/api/business'
import setting from './setting'
import { getBizChannelList } from '@/api/payConfig'
import { MessageBox } from 'element-ui'
// import router from '@/router'

const user = {
  state: {
    token: getToken(),
    agentFlow: {},
    info: null,
    id: null,
    shopId: null,
    avatar: '',
    name: '',
    username: '',
    wechatOpenid: '',
    userSuffix: '',
    businessInfo: '',
    fileBaseUrl: '',
    bisWebLogo: '',
    banBtnList: [],
    features: [],
    allShopList: [], // 所有门店列表
    allManageShopFilterOptions: [], // 所有管理门店筛选条件列表
    manageShopList: [], // 当前用户管理门店列表(可允许包括总部)
    manageShopListExcludeHeadquarters: [], //  当前用户管理门店列表(不包括总部)
    manageDeviceList: [],
    allManageDeviceFilterOptions: [], // 所有管理终端筛选条件列表
    loaded: false,
    manageBizCodeOptions: [],
    channelBizCodeOptions: [], // 当前商户渠道列表
    authentication: null, // 鉴权弹窗
    platformType: null, // 平台类型：2私域商户 3公域平台后台 4公域商户
    platformTypeTitle: null,
    mainShopStatus: false,
    businessResourceBtns: [] // 注意事项：MEMBER_BIND_DEVICE是云南卡卡专项定制
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_AGENT_FLOW: (state, data) => {
      state.agentFlow = data
    },
    SET_MANAGE_SHOP: (state, shopList) => {
      if (state.shopId === 0) {
        // 如果是总店 全部门店
        state.manageShopListExcludeHeadquarters = shopList
        if (state.platformType === 3) {
          // 公域不要总部
          state.manageShopList = [].concat(shopList)
        } else {
          state.manageShopList = [
            {
              id: '0',
              name: '总部',
              icon: state.businessInfo.logoUrl
            }
          ].concat(shopList)
        }
      } else {
        // 其它当前门店
        shopList.some((v) => {
          if (v.id == state.shopId) {
            state.manageShopListExcludeHeadquarters = [v]
            state.manageShopList = [v]
            return true
          }
        })
      }
      state.allShopList = shopList
      state.allManageShopFilterOptions = [
        { id: '', name: '所有门店', icon: state.businessInfo.logoUrl }
      ].concat(state.manageShopList)
    },

    SET_MANAGE_DEVICE: (state, deviceList) => {
      state.manageDeviceList = deviceList
      state.allManageDeviceFilterOptions = [
        { id: '', deviceName: '所有终端', outDeviceNo: '', kdDeviceNo: '' }
      ].concat(deviceList)
    },

    SET_CHANNEL_DEVICE: (state, deviceList) => {
      state.channelBizCodeOptions = deviceList
    },

    SET_MANAGE_FEATURE: (state, featureList) => {
      let { bizCodeOptions } = setting.state
      console.log(
        bizCodeOptions,
        '----------',
        state.businessResourceBtns.includes('MEMBER_BIND_DEVICE')
      )
      if (!state.businessResourceBtns.includes('MEMBER_BIND_DEVICE')) {
        // 云南卡卡相关权限判断
        bizCodeOptions = bizCodeOptions.filter((code) => code.key !== 9117)
      }

      const manageBizCodeOptions = []
      bizCodeOptions.forEach((item) => {
        if (
          item.features.length === 0 ||
          item.features.filter((v) => new Set(featureList).has(v)).length !== 0
        ) {
          manageBizCodeOptions.push(item)
        }
      })
      // console.log(manageBizCodeOptions)
      state.manageBizCodeOptions = manageBizCodeOptions
    },

    SET_USER_INFO: (state, userInfo) => {
      state.info = userInfo
      state.id = userInfo.id
      state.shopId = userInfo.shopId
      state.avatar = userInfo.avatar
      state.name = userInfo.name
      state.username = userInfo.username
      state.wechatOpenid = userInfo.wechatOpenid
      state.userSuffix = userInfo.business.userSuffix
      state.businessInfo = userInfo.business
      state.fileBaseUrl = userInfo.resBaseUrl
      state.businessResourceBtns = userInfo.businessResourceBtns || []
      state.bisWebLogo =
        userInfo.business.oemConfig && userInfo.business.oemConfig.bisWebLogo
          ? userInfo.business.oemConfig.bisWebLogo
          : ''
      state.banBtnList = userInfo.banBtnList || []
      state.features = userInfo.features || []
      state.loaded = true
      state.platformType = userInfo.platformType
      state.platformTypeTitle =
        userInfo.platformType === 3
          ? '公域平台'
          : userInfo.platformType === 2
            ? '商户平台'
            : ''
      state.mainShopStatus = userInfo.mainShopStatus
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.username.trim(), userInfo.password.trim())
          .then((res) => {
            const token = res.data
            setToken(token)
            commit('SET_TOKEN', token)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ dispatch, commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then(async(response) => {
            commit('SET_USER_INFO', response.data)
            Promise.all([
              dispatch('GetManageShop'),
              dispatch('GetFeatureList')
            ]).then((res) => {
              resolve(response)
            })
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户所有管理门店
    GetManageShop({ commit, state }) {
      return new Promise((resolve, reject) => {
        getAllShop()
          .then((res) => {
            const shopList = res.data
            commit('SET_MANAGE_SHOP', shopList)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    // 获取商家所有管理功能
    GetFeatureList({ commit, state }) {
      return new Promise((resolve, reject) => {
        getFeatureList()
          .then((res) => {
            // console.log(res)
            const featureList = []
            res.data.forEach((res) => {
              featureList.push(res.code)
            })
            commit('SET_MANAGE_FEATURE', featureList)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    // 获取用户所有管理门店的终端
    GetManageDevice({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.shopId === 0) {
          getAllDeviceList()
            .then((response) => {
              const deviceList = response.data || []
              commit('SET_MANAGE_DEVICE', deviceList)
              resolve(deviceList)
            })
            .catch((err) => {
              reject(err)
            })
        } else {
          getAllDeviceListByShopId({ shopId: state.shopId })
            .then((response) => {
              const deviceList = response.data || []
              commit('SET_MANAGE_DEVICE', deviceList)
              resolve(deviceList)
            })
            .catch((err) => {
              reject(err)
            })
        }
      })
    },

    // 流量预警信息
    mercFlowAlert({ commit }, data) {
      return new Promise((resolve, reject) => {
        flowAlert(data)
          .then((res) => {
            const agtFlowData = res.data
            // 流量余额
            if (
              agtFlowData.alertFlag == 1 &&
              localStorage.getItem('flowWarnTag') == 'open'
            ) {
              MessageBox.alert(agtFlowData.alertNotice, '提示', {
                confirmButtonText: '我知道了',
                type: 'warning'
              }).then(() => {
                // router.push({
                //   path: '/system/flow-balance',
                //   query: {
                //     showPay: true
                //   }
                // })
              })
              localStorage.setItem('flowWarnTag', 'close')
            }
            commit('SET_AGENT_FLOW', res.data)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户所有渠道商户号
    GetChannelDevice({ commit, state }) {
      return new Promise((resolve, reject) => {
        getBizChannelList()
          .then((response) => {
            const deviceList = response.data || []
            commit('SET_CHANNEL_DEVICE', deviceList)
            resolve(deviceList)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
